//
//  FindCar_TableViewController.m
//  CarEncyclopedia
//
//  Created by lanou3g on 15/7/17.
//  Copyright (c) 2015年 ThighXingClub. All rights reserved.
//

#import "FindCar_TableViewController.h"
#import "TenButton_TableViewCell.h"
#import "LogoCell_TableViewCell.h"
#import "ImageDownLoader.h"
#import "FindCar_Details_TableViewController.h"
#import "ReceiveData.h"
#import "FindCar_Details_TableViewController.h"
#define CarLogo @"http://baojia.qichecdn.com/priceapi3.9.2/services/cars/brands?app=2&platform=1&version=3.9.4&ts=0"
@interface FindCar_TableViewController ()

@property(nonatomic,retain)NSDictionary *CarDic;
@property(nonatomic,retain)NSArray *brandlistArray;
@property(nonatomic,retain)NSArray *listArray;
@property(nonatomic,retain)NSArray *hotbrandlistArray;
@property(nonatomic,retain)NSMutableArray *hotbrandlistNameArray;
@property(nonatomic,retain)NSMutableArray *letterArr;
@end

@implementation FindCar_TableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
    
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
     self.letterArr=[NSMutableArray array];
     self.hotbrandlistNameArray=[NSMutableArray array];
    
     self.view.backgroundColor=[UIColor colorWithRed:255/255.0 green:192/255.0 blue:203/255.0 alpha:1];
    
    //索引栏透明
    self.tableView.sectionIndexBackgroundColor=[UIColor clearColor];
  
    
    [self.tableView registerNib:[UINib nibWithNibName:@"TenButton_TableViewCell" bundle:nil] forCellReuseIdentifier:@"cell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"LogoCell_TableViewCell" bundle:nil] forCellReuseIdentifier:@"cell1"];
    
    //解析数据
    NSURL *url=[NSURL URLWithString:CarLogo];
    NSURLRequest *request=[NSURLRequest requestWithURL:url];
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        if (data) {
            self.CarDic=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            
            NSDictionary *dic=[self.CarDic objectForKey:@"result"];
            
            self.brandlistArray=[dic objectForKey:@"brandlist"];
            
            
            for (int i= 0; i<self.brandlistArray.count; i++) {
                
                NSString *letter = [[self.brandlistArray objectAtIndex:i] objectForKey:@"letter"];
                
                [self.letterArr addObject:letter];
             
            }
            
       
            NSDictionary *hotbrand_dic=[dic objectForKey:@"hotbrand"];

            
            self.hotbrandlistArray=[hotbrand_dic objectForKey:@"hotbrandlist"];

           
         
          [self.tableView reloadData];
     
           
        }
        
    }];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



#pragma mark - Table view data source


//区域标题设定
-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    
    if (section==0) {
        
        NSString *HotCar=@"热门品牌";
        return HotCar;
    }
    
    
    
    
    NSString *Header=[self.brandlistArray[section-1] objectForKey:@"letter"];
    
    
    return Header;
    
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    

    // Return the number of sections.
    return self.brandlistArray.count+1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    
    if (section==0) {
        
        return 1;
        
    }
    

    
    self.listArray=[self.brandlistArray[section-1] objectForKey:@"list"];
    
   
    
    
    // Return the number of rows in the section.
    return self.listArray.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
 
   
    if (indexPath.section==0 && indexPath.row==0) {
        
        
        TenButton_TableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:@"cell"];
   
       //--------大众
        cell.VolkSwagenLabel.text = [self.hotbrandlistArray[0] objectForKey:@"name"];
        NSString *VolkSwagenImgurl=[self.hotbrandlistArray[0] objectForKey:@"imgurl"];
        [cell.VolkSwagenButton addTarget:self action:@selector(VolkSwagen) forControlEvents:UIControlEventTouchUpInside];
        
        ImageDownLoader *imageDownLoader=[ImageDownLoader new];
        
        [imageDownLoader requestImageUrl:VolkSwagenImgurl successBlock:^(NSData *Data) {
            cell.VolkSwagenImage.image=[UIImage  imageWithData:Data];
            
        } errorBlock:^(NSError *Error) {
            NSLog(@"Error=%@",Error);
            
        }];
        [cell.VolkSwagenButton addTarget:self action:@selector(PushToNextView:) forControlEvents:UIControlEventTouchUpInside];
        
    //--------丰田
        cell.ToyotaLabel.text = [self.hotbrandlistArray[1] objectForKey:@"name"];
        NSString *ToyotaImgurl=[self.hotbrandlistArray[1] objectForKey:@"imgurl"];

        [imageDownLoader requestImageUrl:ToyotaImgurl successBlock:^(NSData *Data) {
            cell.ToyotaImage.image=[UIImage  imageWithData:Data];
            
        } errorBlock:^(NSError *Error) {
            NSLog(@"Error=%@",Error);
            
        }];
        [cell.ToyotaButton addTarget:self action:@selector(PushToNextView:) forControlEvents:UIControlEventTouchUpInside];
    //--------现代
        cell.ModernLabel.text = [self.hotbrandlistArray[2] objectForKey:@"name"];
        NSString *ModernImgurl=[self.hotbrandlistArray[2] objectForKey:@"imgurl"];
        
        [imageDownLoader requestImageUrl:ModernImgurl successBlock:^(NSData *Data) {
            cell.ModernImage.image=[UIImage  imageWithData:Data];
            
        } errorBlock:^(NSError *Error) {
            NSLog(@"Error=%@",Error);
            
        }];
        [cell.ModernButton addTarget:self action:@selector(PushToNextView:) forControlEvents:UIControlEventTouchUpInside];
    //--------本田
        cell.HondaLabel.text = [self.hotbrandlistArray[3] objectForKey:@"name"];
        NSString *HondaLaImgurl=[self.hotbrandlistArray[3] objectForKey:@"imgurl"];
       
        [imageDownLoader requestImageUrl:HondaLaImgurl successBlock:^(NSData *Data) {
            cell.HondaImage.image=[UIImage  imageWithData:Data];
            
        } errorBlock:^(NSError *Error) {
            NSLog(@"Error=%@",Error);
            
        }];
        [cell.HondaButton addTarget:self action:@selector(PushToNextView:) forControlEvents:UIControlEventTouchUpInside];
    //--------奥迪
        cell.AudiLabel.text = [self.hotbrandlistArray[4] objectForKey:@"name"];
        NSString *AudiImgurl=[self.hotbrandlistArray[4] objectForKey:@"imgurl"];
        
        [imageDownLoader requestImageUrl:AudiImgurl successBlock:^(NSData *Data) {
            cell.AudiImage.image=[UIImage  imageWithData:Data];
            
        } errorBlock:^(NSError *Error) {
            NSLog(@"Error=%@",Error);
            
        }];
        [cell.AudiButton addTarget:self action:@selector(PushToNextView:) forControlEvents:UIControlEventTouchUpInside];
    //--------福特
        cell.FordLabel.text = [self.hotbrandlistArray[5] objectForKey:@"name"];
        NSString *FordImgurl=[self.hotbrandlistArray[5] objectForKey:@"imgurl"];
        
        [imageDownLoader requestImageUrl:FordImgurl successBlock:^(NSData *Data) {
            cell.FordImage.image=[UIImage  imageWithData:Data];
            
        } errorBlock:^(NSError *Error) {
            NSLog(@"Error=%@",Error);
            
        }];
        [cell.FordButton addTarget:self action:@selector(PushToNextView:) forControlEvents:UIControlEventTouchUpInside];

    //--------别克
        cell.BuickLabel.text = [self.hotbrandlistArray[6] objectForKey:@"name"];
        NSString *BuickImgurl=[self.hotbrandlistArray[6] objectForKey:@"imgurl"];
        
        [imageDownLoader requestImageUrl:BuickImgurl successBlock:^(NSData *Data) {
            cell.BuickImage.image=[UIImage  imageWithData:Data];
            
        } errorBlock:^(NSError *Error) {
            NSLog(@"Error=%@",Error);
            
        }];
        [cell.BuickButton addTarget:self action:@selector(PushToNextView:) forControlEvents:UIControlEventTouchUpInside];

    //--------长安
        cell.ChangAnLabel.text = [self.hotbrandlistArray[7] objectForKey:@"name"];
        NSString *ChangAnImgurl=[self.hotbrandlistArray[7] objectForKey:@"imgurl"];
        
        [imageDownLoader requestImageUrl:ChangAnImgurl successBlock:^(NSData *Data) {
            cell.ChangAnImage.image=[UIImage  imageWithData:Data];
            
        } errorBlock:^(NSError *Error) {
            NSLog(@"Error=%@",Error);
            
        }];
        [cell.ChangAnButton addTarget:self action:@selector(PushToNextView:) forControlEvents:UIControlEventTouchUpInside];

    //--------起亚
        cell.KiaLabel.text = [self.hotbrandlistArray[8] objectForKey:@"name"];
        NSString *KiaImgurl=[self.hotbrandlistArray[8] objectForKey:@"imgurl"];
        
        [imageDownLoader requestImageUrl:KiaImgurl successBlock:^(NSData *Data) {
            cell.KiaImage.image=[UIImage  imageWithData:Data];
            
        } errorBlock:^(NSError *Error) {
            NSLog(@"Error=%@",Error);
            
        }];
        [cell.KiaButton addTarget:self action:@selector(PushToNextView:) forControlEvents:UIControlEventTouchUpInside];

    //--------哈佛
        cell.HarvardLabel.text = [self.hotbrandlistArray[9] objectForKey:@"name"];
        NSString *HarvardImgurl=[self.hotbrandlistArray[9] objectForKey:@"imgurl"];
        
        [imageDownLoader requestImageUrl:HarvardImgurl successBlock:^(NSData *Data) {
            cell.HarvardImage.image=[UIImage  imageWithData:Data];
            
        } errorBlock:^(NSError *Error) {
            NSLog(@"Error=%@",Error);
            
        }];
        [cell.HarvardButton addTarget:self action:@selector(PushToNextView:) forControlEvents:UIControlEventTouchUpInside];

        
        
        
   
        return cell;
        
    }
        
        
    LogoCell_TableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:@"cell1"];
    
    
    NSDictionary *brandlistDic=[self.brandlistArray objectAtIndex:indexPath.section -1];

//    NSLog(@"%@",brandlistDic);
    
    NSArray *listArray=[brandlistDic objectForKey:@"list"];
//    NSLog(@"%lu",listArray.count);
    
    NSDictionary *ListDic=[listArray objectAtIndex:indexPath.row];
    
    cell.CarLabel.text=[ListDic objectForKey:@"name"];
//    NSLog(@"%@",cell.CarLabel.text);
    
    
    //图片地址
    NSString *Car_ImageUrl_Str=[ListDic objectForKey:@"imgurl"];
    
    ImageDownLoader *imageDown=[ImageDownLoader new];
    
    [imageDown requestImageUrl:Car_ImageUrl_Str successBlock:^(NSData *Data) {
        cell.TitleImage.image=[UIImage imageWithData:Data];
    } errorBlock:^(NSError *Error) {
        
    }];
    
       return cell;
    
   
}

-(void)VolkSwagen{
    
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section==0  &&   indexPath.row==0) {
        
        
        return 150;
        
    }
  
    return 55;
    
}

//选中cell触发的方法
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    
    if (indexPath.section==0 && indexPath.row==0) {
        UIAlertView *promptView=[[UIAlertView alloc] initWithTitle:@"提示" message:@"亲哟,请点击图标" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [promptView show];
    }
   
    else{
        
    
    FindCar_Details_TableViewController *FDC_VC=[FindCar_Details_TableViewController new];
  
    NSDictionary *brandlistDic=[self.brandlistArray objectAtIndex:indexPath.section -1];
    
    //    NSLog(@"%@",brandlistDic);
    
    NSArray *listArray=[brandlistDic objectForKey:@"list"];
    //    NSLog(@"%lu",listArray.count);
    
    NSDictionary *ListDic=[listArray objectAtIndex:indexPath.row];
    
    FDC_VC.receiveID=[ListDic objectForKey:@"id"];
//    NSLog(@"ID=%@",FDC_VC.receiveID);
    
   [self.navigationController pushViewController:FDC_VC animated:YES];
        
    }
   
}


//第一份分区10个Button点击触发的方法
-(void)PushToNextView:(UIButton *)button{
    
    FindCar_Details_TableViewController *FDT_VC=[FindCar_Details_TableViewController new];
    

    
    for (int i =1; i<11; i++) {
        
        if (button.tag == i) {
            FDT_VC.receiveID=[self.hotbrandlistArray[i-1] objectForKey:@"brandid"];
        }
    }
    
    
  
    [self.navigationController pushViewController:FDT_VC animated:YES];
    
    
    
    
}


//创建分区索引标题
-(NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView{
    
    if (self.letterArr.count != 0) {
        [self.letterArr insertObject:@"#" atIndex:0];

    }
    
    return self.letterArr;
    
}


-(NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index{

    return index;
 
}
/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
